package com.farm.project.controller;

import com.farm.project.domain.Project;
import com.farm.project.service.ProjectServiceInter;
import com.farm.sfile.WdapFileServiceInter;
import com.farm.sfile.domain.ex.PersistFile;
import com.farm.sfile.utils.DownloadUtils;
import com.farm.sfile.utils.FarmDocFiles;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import com.farm.web.easyui.EasyUiUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpSession;
import com.farm.core.page.RequestMode;
import com.farm.cbtg.domain.Appcatalog;
import com.farm.cbtg.service.AppcatalogServiceInter;
import com.farm.core.page.OperateType;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.core.page.ViewMode;
import com.farm.web.WebUtils;

/* *
 *功能：工程项目控制层
 *详细：
 *
 *版本：v0.1
 *作者：FarmCode代码工程
 *日期：20150707114057
 *说明：
 */
@RequestMapping("/project")
@Controller
public class ProjectController extends WebUtils {
	private final static Logger log = Logger.getLogger(ProjectController.class);
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private AppcatalogServiceInter appCatalogServiceImpl;
	@Resource
	private WdapFileServiceInter wdapFileServiceImpl;

	/**
	 * 查询结果集合
	 * 
	 * @return
	 */
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> queryall(DataQuery query, HttpServletRequest request) {
		try {
			DBRule exportTypeDB = query.getAndRemoveRule("CATALOGID");
			if (exportTypeDB != null) {
				Appcatalog type = appCatalogServiceImpl.getAppcatalogEntity(exportTypeDB.getValue());
				if (type != null) {
					query.addRule(new DBRule("B.TREECODE", type.getTreecode(), "like-"));
				}
			}
			query = EasyUiUtils.formatGridQuery(request, query);
			DataResult result = projectServiceImpl.createProjectSimpleQuery(query).search();
			result.runDictionary("1:创建,2:发布,0:禁用", "PSTATE");
			return ViewMode.getInstance().putAttrs(EasyUiUtils.formatGridData(result)).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交修改数据
	 * 
	 * @return
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> editSubmit(Project entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = projectServiceImpl.editProjectEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).putAttr("entity", entity).returnObjMode();

		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.UPDATE).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 提交新增数据
	 * 
	 * @return
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> addSubmit(Project entity, HttpSession session) {
		// TODO 自动生成代码,修改后请去除本注释
		try {
			entity = projectServiceImpl.insertProjectEntity(entity, getCurrentUser(session));
			return ViewMode.getInstance().setOperate(OperateType.ADD).putAttr("entity", entity).returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setOperate(OperateType.ADD).setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 删除数据
	 * 
	 * @return
	 */
	@RequestMapping("/del")
	@ResponseBody
	public Map<String, Object> delSubmit(String ids, HttpSession session) {
		try {
			for (String id : parseIds(ids)) {
				projectServiceImpl.deleteProjectEntity(id, getCurrentUser(session));
			}
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	@RequestMapping("/list")
	public ModelAndView index(HttpSession session) {
		return ViewMode.getInstance().returnModelAndView("project/ProjectResult");
	}

	/**
	 * 显示详细信息（修改或浏览时）
	 *
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView view(RequestMode pageset, String ids, String catalogId) {
		try {
			switch (pageset.getOperateType()) {
			case (0): {// 查看
				Project project = projectServiceImpl.getProjectEntity(ids);
				Appcatalog catalog = appCatalogServiceImpl.getAppcatalogEntity(project.getCatalogid());
				return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", project)
						.putAttr("catalog", catalog).returnModelAndView("project/ProjectForm");
			}
			case (1): {// 新增
				Appcatalog catalog = appCatalogServiceImpl.getAppcatalogEntity(catalogId);
				return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("catalog", catalog)
						.returnModelAndView("project/ProjectForm");
			}
			case (2): {// 修改

				Project project = projectServiceImpl.getProjectEntity(ids);
				Appcatalog catalog = appCatalogServiceImpl.getAppcatalogEntity(project.getCatalogid());
				return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", project)
						.putAttr("catalog", catalog).returnModelAndView("project/ProjectForm");
			}
			default:
				break;
			}
			return ViewMode.getInstance().returnModelAndView("project/ProjectForm");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("project/ProjectForm");
		}
	}

	/**
	 * 导入导出表单
	 *
	 * @return
	 */
	@RequestMapping("/sycnForm")
	public ModelAndView sycnForm(RequestMode pageset, String projectid, String catalogId) {
		try {
			Project project = projectServiceImpl.getProjectEntity(projectid);
			Appcatalog catalog = null;
			if (project != null) {
				catalog = appCatalogServiceImpl.getAppcatalogEntity(project.getCatalogid());
			}
			return ViewMode.getInstance().putAttr("pageset", pageset).putAttr("entity", project)
					.putAttr("catalog", catalog).returnModelAndView("project/ProjectSycn");

		} catch (Exception e) {
			return ViewMode.getInstance().setError(e + e.getMessage(), e).returnModelAndView("project/ProjectSycn");
		}
	}

	/**
	 * 下載文件夹中文件(导出项目)
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	@RequestMapping("/download")
	public void download(String projectid, HttpServletRequest request, HttpServletResponse response)
			throws FileNotFoundException, IOException {
		Project project = projectServiceImpl.getProjectEntity(projectid);
		String json = projectServiceImpl.getProjectJson(projectid);
		DownloadUtils.downloadFile(json, project.getName() + ".json", response);
	}

	/**
	 * 导入项目
	 * 
	 * @return
	 */
	@RequestMapping("/import")
	@ResponseBody
	public Map<String, Object> importProject(String fileid, HttpSession session) {
		try {
			PersistFile pfile = wdapFileServiceImpl.getPersistFile(fileid);
			String json = FarmDocFiles.readFileText(pfile.getFile());
			projectServiceImpl.importProjectByJson(json, getCurrentUser(session));
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}

	/**
	 * 移动节点
	 * 
	 * @return
	 */
	@RequestMapping("/moveNodeSubmit")
	@ResponseBody
	public Object moveTreeNodeSubmit(String ids, String id, HttpSession session) {
		try {
			projectServiceImpl.updateCatalog(ids, id, getCurrentUser(session));
			return ViewMode.getInstance().returnObjMode();
		} catch (Exception e) {
			log.error(e.getMessage());
			return ViewMode.getInstance().setError(e.getMessage(), e).returnObjMode();
		}
	}
}
